<?php

namespace app\admin\controller\hospital;

use app\admin\library\Auth;
use app\api\controller\Distance;
use app\common\controller\Api;
use app\common\controller\Backend;
use app\common\model\GoodsHospital;
use fast\Random;
use OSS\OssClient;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Controller;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Hospital extends Backend
{

    /**
     * Hospital模型对象
     * @var \app\common\model\Hospital
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Hospital;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        $params['province']=\db('marea')->where(['id'=>$params['province_id'],'level'=>1])->value('name');
        $params['city']=\db('marea')->where(['id'=>$params['city_id'],'level'=>2,'pid'=>$params['province_id']])->value('name');
        $params['area']=\db('marea')->where(['id'=>$params['area_id'],'level'=>3,'pid'=>$params['city_id']])->value('name');
        $distance = new Distance();
        $address = $params['province'].$params['city'].$params['area'].$params['address'];
        $m = $distance->getLat($address);
        if(!empty($m))
        {
            if($m['status']==0){
                if(isset($m['result']['location'])){
                    $params['lat']=$m['result']['location']['lat'];
                    $params['lng']=$m['result']['location']['lng'];
                }else{
                    $this->error('未获取地址的经纬度');
                }
            }else{
                $this->error($m['message']);
            }

        }else{
            $this->error('地址有误');
        }

        $this->model->save($params);
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            Db::commit();
            (new GeneralTimes())->savesAppoint($this->model->id);
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        $params['province']=\db('marea')->where(['id'=>$params['province_id'],'level'=>1])->value('name');
        $params['city']=\db('marea')->where(['id'=>$params['city_id'],'level'=>2,'pid'=>$params['province_id']])->value('name');
        $params['area']=\db('marea')->where(['id'=>$params['area_id'],'level'=>3,'pid'=>$params['city_id']])->value('name');
       if($params['province']!=$row['province']||$params['city']!=$row['city']||$row['area']!=$params['area']||$params['address']!=$params['address']){
           $distance = new Distance();
           $address = $params['province'].$params['city'].$params['area'].$params['address'];
           $m = $distance->getLat($address);
           if(!empty($m))
           {
               if($m['status']==0){
                   if(isset($m['result']['location'])){
                       $params['lat']=$m['result']['location']['lat'];
                       $params['lng']=$m['result']['location']['lng'];
                   }else{
                       $this->error('未获取地址的经纬度');
                   }
               }else{
                   $this->error($m['message']);
               }

           }else{
               $this->error('地址有误');
           }
       }
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                GoodsHospital::where(['hospital_id'=>$item['id']])->delete();
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        try{
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $data=$currentSheet->toArray();
        }catch(\Exception $e){

            $this->error('加载文件发生错误："'.pathinfo($filePath,PATHINFO_BASENAME).'": '.$e->getMessage());

        }

        //加载文件
        $insert = [];
        try {

//            if (!$PHPExcel = $reader->load($filePath)) {
//                $this->error(__('Unknown data format'));
//            }
            $imageFilePath=ROOT_PATH.'/public/uploads/images/' ;//图片保存目录
            if (!file_exists ( $imageFilePath )) {
                mkdir("$imageFilePath", 0777, true);
            }
            foreach ($currentSheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());//获取图片所在行和列
                $imageFileName = Random::uuid();
                if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
                    ob_start();
                    call_user_func(
                        $drawing->getRenderingFunction(),
                        $drawing->getImageResource()
                    );
                    $imageContents = ob_get_contents();
                    ob_end_clean();
                    switch ($drawing->getMimeType()) {
                        case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG :
                            $extension = 'png';
                            break;
                        case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
                            $extension = 'gif';
                            break;
                        case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG :
                            $extension = 'jpg';
                            break;
                    }
                } else {
                    $zipReader = fopen($drawing->getPath(), 'r');
                    $imageContents = '';
                    while (!feof($zipReader)) {
                        $imageContents .= fread($zipReader, 2048);
                    }
                    fclose($zipReader);
                    $extension = $drawing->getExtension();
                }
                /* Getting Column and Row name */

                $c = $drawing->getCoordinates();
                preg_match_all('!\d+!', $c, $matches);
                $column = $matches[0][0];
                $row = strstr($c, $column, true);
                $dir =DS.'xinyanguang'.DS.date("Ymd").DS;

                if (!file_exists ('.' .$dir)){

                    mkdir ('.' . $dir , 0777, true );
                }
                $path = '/xinyanguang/'.date("Ymd").'/'.Random::uuid().'.'.$extension;
                $splInfo=file_put_contents(".".$path,$imageContents);
                if($splInfo){
                    $filePath1 = ROOT_PATH . 'public' . $path;
                    $config = get_addon_config('alioss');
                    $accessKeyId = $config['accessKeyId'];
                    $accessKeySecret = $config['accessKeySecret'];
                    $endpoint = $config['endpoint'];
                    $bucket = $config['bucket'];
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                    $ossClient->putObject($bucket, ltrim($path, '/'),$imageContents);

                }

                $currentSheet->setCellValue($startColumn . $startRow, $path);
                $startColumn = $this->ABC2decimal($startColumn);//由于图片所在位置的列号为字母，转化为数字
                if($startColumn==1){
                    $data[$startRow-1][$startColumn][]= $path;//把图片插入到数组中
                }else{
                    $data[$startRow-1][$startColumn]= $path;
                }



            }


            //处理图片

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $fields[] = $val;
                }
            }

            $ms_names=[];
            for ($currentRow = 1; $currentRow < $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 0; $currentColumn <$maxColumnNumber; $currentColumn++) {
                    // $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $val = $data[$currentRow][$currentColumn];
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];

                $temp = array_combine($fields, $values);

                // die;

                foreach ($temp as $k => $v) {





                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = is_array($v)?implode(',',$v):$v;

                    }


                }


                if ($row) {



                    if(empty($row['hospital_name'])){
                        $this->error('请输入医院名称');
                    }


                    $time = explode('-',$row['endtime']);


                    if(count($time)!=2){
                        $this->error('请输入营业时间');
                    }else{
                        $row['startime']=$time[0];
                        $row['endtime']=$time[1];
                        if(strtotime($row['startime'])>=strtotime($row['endtime'])){
                            $this->error('营业开始时间应小于结束时间');
                        }

                    }

                    $tag_ids=explode(',', $row['tag_ids']);
                    if(count($tag_ids)!=count(array_unique($tag_ids))){
                        $this->error('服务类型重复');
                    }
                    $tags=[];
                    foreach ($tag_ids as $k=>$v){
                        $mid=\db('goods_tags')->where(['tag_name'=>$v,'way'=>2])->value('id');
                        if(!$mid){
                            $this->error('服务类型');
                        }else{
                            $tags[]=$mid;
                        }
                    }
                    $row['tag_ids']=implode(',',$tags);


                    $row['province_id']=db('marea')
                        ->where(['name'=>$row['province'],'level'=>1])
                        ->value('id');
                    if(empty($row['province_id'])){
                        $this->error('未查询到省');
                    }


                    $row['city_id']=db('marea')
                        ->where(['name'=>$row['city'],'level'=>2,'pid'=>$row['province_id']])
                        ->value('id');
                    if(empty($row['city_id'])){
                        $this->error('未查询到市');
                    }

                    $row['area_id']=db('marea')
                        ->where(['name'=>$row['area'],'level'=>3,'pid'=>$row['city_id']])
                        ->value('id');
                    if(empty($row['area_id'])){
                        $this->error('未查询到区');
                    }
                    if(in_array($row['hospital_name'].$row['area_id'],$ms_names)){
                        $this->error('医院数据重复');
                    }
                    $count_m=$this->model->where(['hospital_name'=>$row['hospital_name'],'area_id'=>$row['area_id']])->count();
                    if($count_m>0){
                        $this->error('医院数据重复');
                    }
                    $ms_names[]=$row['hospital_name'].$row['area_id'];

                    $distance = new Distance();
                    $address = $row['province'].$row['city'].$row['area'].$row['address'];

                    $m = $distance->getLat($address);


                    if(!empty($m))
                    {
                        if($m['status']==0){
                            if(isset($m['result']['location'])){
                                $row['lat']=$m['result']['location']['lat'];
                                $row['lng']=$m['result']['location']['lng'];
                            }else{
                                $this->error('未获取地址的经纬度');
                            }
                        }else{
                            $this->error($m['message']);
                        }

                    }else{
                        $this->error('地址有误');
                    }
                    $row['createtime']=time();
                    $row['updatetime']=time();


                    $insert[] = $row;
                    $res = $this->model->insertGetId($row);
                    (new GeneralTimes())->savesAppoint($res);





                }
            }

        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }

            //$res =$this->model->saveAll($insert);

        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
    public function ABC2decimal($abc)
    {
        $ten = 0;
        $len = strlen($abc);
        for($i=1;$i<=$len;$i++){
            $char = substr($abc,0-$i,1);//反向获取单个字符

            $int = ord($char);
            $ten += ($int-65)*pow(26,$i-1);
        }
        return $ten;
    }


    public function updatetags($ids = null)
    {
        $row = $this->model->where('id','in',$ids)->select();
        if (count($row)<0) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证

            if(empty($params['tag_ids'])){
                $this->error('请选择服务类型！');
            }
            $params['updatetime']=time();
            $result = $this->model->where('id','in',$ids)->update($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
